package cn.com.okgo.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import cn.com.okgo.OkGo;
import cn.com.okgo.model.HttpHeaders;
import cn.com.okgo.model.HttpParams;
import cn.com.okgo.model.Bytes;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by luwenlong on 2017/8/28.
 */

public class HttpUtils {
    /**
     * 判断是否有网络连接
     *
     * @return
     */
    public static boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) OkGo.getContext()
                .getSystemService( Context.CONNECTIVITY_SERVICE );
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    /**
     * 根据文件名获取MIME类型
     */
    public static MediaType guessMimeType(String fileName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        fileName = fileName.replace( "#", "" );   //解决文件名中含有#号异常的问题
        String contentType = fileNameMap.getContentTypeFor( fileName );
        if (contentType == null) {
            return HttpParams.MEDIA_TYPE_STREAM;
        }
        return MediaType.parse( contentType );
    }

    /**
     * 通用的拼接请求头
     */
    public static Request.Builder appendHeaders(Request.Builder builder, HttpHeaders headers) {
        if (headers.headersMap.isEmpty()) return builder;
        Headers.Builder headerBuilder = new Headers.Builder();
        try {
            for (Map.Entry<String, String> entry : headers.headersMap.entrySet()) {
                //对头信息进行 utf-8 编码,防止头信息传中文,这里暂时不编码,可能出现未知问题,如有需要自行编码
//                String headerValue = URLEncoder.encode(entry.getValue(), "UTF-8");
                headerBuilder.add( entry.getKey(), entry.getValue() );
            }
        } catch (Exception e) {
        }
        builder.headers( headerBuilder.build() );
        return builder;
    }

    /**
     * 将传递进来的参数拼接成 url
     */
    public static String createUrlFromParams(String url, Map<String, List<String>> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append( url );
            if (url.indexOf( '&' ) > 0 || url.indexOf( '?' ) > 0) sb.append( "&" );
            else sb.append( "?" );
            for (Map.Entry<String, List<String>> urlParams : params.entrySet()) {
                List<String> urlValues = urlParams.getValue();
                for (String value : urlValues) {
                    //对参数进行 utf-8 编码,防止信息传中文
                    String urlValue = URLEncoder.encode( value, "UTF-8" );
                    sb.append( urlParams.getKey() ).append( "=" ).append( urlValue ).append( "&" );
                }
            }
            sb.deleteCharAt( sb.length() - 1 );
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
        }
        return url;
    }

    /**
     * 生成类似表单的请求体
     */
    public static RequestBody generateMultipartRequestBody(HttpParams params) {
        if (params.fileParamsMap.isEmpty() && params.byteParamsList.isEmpty()) {
            //表单提交，没有文件、byte
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (String key : params.urlParamsMap.keySet()) {
                List<String> urlValues = params.urlParamsMap.get( key );
                for (String value : urlValues) {
                    bodyBuilder.addEncoded( key, value );
                }
            }
            return bodyBuilder.build();
        } else if (!params.fileParamsMap.isEmpty() && params.byteParamsList.isEmpty()) {
            //表单提交，有文件,没有byte
            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType( MultipartBody.FORM );
            //拼接键值对
            if (!params.urlParamsMap.isEmpty()) {
                for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
                    List<String> urlValues = entry.getValue();
                    for (String value : urlValues) {
                        multipartBodybuilder.addFormDataPart( entry.getKey(), value );
                    }
                }
            }
            //拼接文件
            for (Map.Entry<String, List<HttpParams.FileWrapper>> entry : params.fileParamsMap.entrySet()) {
                List<HttpParams.FileWrapper> fileValues = entry.getValue();
                for (HttpParams.FileWrapper fileWrapper : fileValues) {
                    RequestBody fileBody = RequestBody.create( fileWrapper.contentType, fileWrapper.file );
                    multipartBodybuilder.addFormDataPart( entry.getKey(), fileWrapper.fileName, fileBody );
                }
            }
            return multipartBodybuilder.build();
        } else if (params.fileParamsMap.isEmpty() && !params.byteParamsList.isEmpty()) {
            //表单提交，没有文件,有byte
            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType( MultipartBody.FORM );
            //拼接键值对
            if (!params.urlParamsMap.isEmpty()) {
                for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
                    List<String> urlValues = entry.getValue();
                    for (String value : urlValues) {
                        multipartBodybuilder.addFormDataPart( entry.getKey(), value );
                    }
                }
            }

            //拼接byte
            for (Bytes postByte : params.byteParamsList) {
                RequestBody byteBody = RequestBody.create( HttpParams.MEDIA_TYPE_STREAM, postByte.bytes );
                multipartBodybuilder.addFormDataPart( postByte.key, postByte.fileName, byteBody );
            }
            return multipartBodybuilder.build();

        } else {
            //表单提交，有文件,有byte
            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType( MultipartBody.FORM );
            //拼接键值对
            if (!params.urlParamsMap.isEmpty()) {
                for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
                    List<String> urlValues = entry.getValue();
                    for (String value : urlValues) {
                        multipartBodybuilder.addFormDataPart( entry.getKey(), value );
                    }
                }
            }
            //拼接文件
            for (Map.Entry<String, List<HttpParams.FileWrapper>> entry : params.fileParamsMap.entrySet()) {
                List<HttpParams.FileWrapper> fileValues = entry.getValue();
                for (HttpParams.FileWrapper fileWrapper : fileValues) {
                    RequestBody fileBody = RequestBody.create( fileWrapper.contentType, fileWrapper.file );
                    multipartBodybuilder.addFormDataPart( entry.getKey(), fileWrapper.fileName, fileBody );
                }
            }

            //拼接byte
            for (Bytes postByte : params.byteParamsList) {
                RequestBody byteBody = RequestBody.create( HttpParams.MEDIA_TYPE_STREAM, postByte.bytes );
                multipartBodybuilder.addFormDataPart( postByte.key, postByte.fileName, byteBody );
            }
            return multipartBodybuilder.build();
        }
    }
}
